<template>
  <div class="coupon-records">
    <!-- 页面标题 -->
    <!-- <div class="page-header">
      <h2>核销记录</h2>
      <p>查看和管理优惠券核销历史记录</p>
    </div> -->

    <!-- 搜索条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" size="small">
        <el-form-item>
          <el-select
            v-model="searchForm.merchant_id"
            placeholder="请选择商户"
            style="width: 200px;"
            clearable
            filterable
            :loading="merchantLoading"
          >
            <el-option
              v-for="merchant in merchantList"
              :key="merchant.id"
              :label="`${merchant.merchant_name} (ID: ${merchant.id})`"
              :value="merchant.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="searchForm.coupon_code"
            placeholder="优惠券代码"
            style="width: 150px;"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="核销开始日期"
            end-placeholder="核销结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 240px;"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="searchForm.operated_by_merchant_staff"
            placeholder="操作员工"
            style="width: 120px;"
            clearable
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="loadRecords" :loading="loading">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="exportRecords" :loading="exportLoading">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <i class="el-icon-tickets"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statsData.total_records || 0 }}</div>
                <div class="stat-label">总记录数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon amount">
                <i class="el-icon-money"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">¥{{ statsData.total_amount || '0.00' }}</div>
                <div class="stat-label">总消费金额</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon discount">
                <i class="el-icon-discount"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">¥{{ statsData.total_discount || '0.00' }}</div>
                <div class="stat-label">总优惠金额</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 记录列表 -->
    <el-card class="records-card">
      <div slot="header" class="clearfix">
        <span>核销记录列表</span>
        <div style="float: right;">
          <el-button type="text" @click="loadRecords">刷新</el-button>
        </div>
      </div>

      <el-table 
        :data="records" 
        v-loading="loading"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="记录ID" width="80" sortable="custom"></el-table-column>
        
        <el-table-column prop="coupon_code" label="优惠券代码" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="viewCouponDetail(scope.row.coupon_code)">
              {{ scope.row.coupon_code }}
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="coupon_name" label="优惠券名称" width="180"></el-table-column>
        
        <el-table-column label="金额信息" width="200">
          <template slot-scope="scope">
            <div class="amount-info">
              <div>原价: ¥{{ scope.row.original_amount || '0.00' }}</div>
              <div>优惠: ¥{{ scope.row.discount_amount || '0.00' }}</div>
              <div><strong>实付: ¥{{ scope.row.consume_amount || '0.00' }}</strong></div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="consume_time" label="核销时间" width="160" sortable="custom"></el-table-column>
        
        <el-table-column prop="operated_by_merchant_staff" label="操作员工" width="120"></el-table-column>
        
        <el-table-column prop="consume_location" label="核销地点" width="150"></el-table-column>
        
        <el-table-column label="核销类型" width="100">
          <template slot-scope="scope">
            <el-tag :type="getConsumeTypeTag(scope.row.consume_type)">
              {{ getConsumeTypeText(scope.row.consume_type) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="viewRecord(scope.row)">查看详情</el-button>
            <el-dropdown @command="handleCommand" trigger="click">
              <el-button type="text">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{action: 'revoke', row: scope.row}">撤销核销</el-dropdown-item>
                <el-dropdown-item :command="{action: 'print', row: scope.row}">打印凭证</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 记录详情对话框 -->
    <el-dialog
      title="核销记录详情"
      :visible.sync="detailDialogVisible"
      width="800px"
    >
      <div v-if="selectedRecord">
        <el-descriptions border :column="2">
          <el-descriptions-item label="记录ID">{{ selectedRecord.id }}</el-descriptions-item>
          <el-descriptions-item label="优惠券代码">{{ selectedRecord.coupon_code }}</el-descriptions-item>
          <el-descriptions-item label="优惠券名称">{{ selectedRecord.coupon_name }}</el-descriptions-item>
          <el-descriptions-item label="优惠券描述">{{ selectedRecord.coupon_description }}</el-descriptions-item>
          <el-descriptions-item label="原价金额">¥{{ selectedRecord.original_amount || '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="优惠金额">¥{{ selectedRecord.discount_amount || '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="实际消费">¥{{ selectedRecord.consume_amount || '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="核销时间">{{ selectedRecord.consume_time }}</el-descriptions-item>
          <el-descriptions-item label="核销类型">{{ getConsumeTypeText(selectedRecord.consume_type) }}</el-descriptions-item>
          <el-descriptions-item label="核销渠道">{{ selectedRecord.consume_channel }}</el-descriptions-item>
          <el-descriptions-item label="操作员工">{{ selectedRecord.operated_by_merchant_staff }}</el-descriptions-item>
          <el-descriptions-item label="核销地点">{{ selectedRecord.consume_location }}</el-descriptions-item>
          <el-descriptions-item label="验证码">{{ selectedRecord.verification_code || '无' }}</el-descriptions-item>
          <el-descriptions-item label="用户UnionID">{{ selectedRecord.user_union_id || '无' }}</el-descriptions-item>
          <el-descriptions-item label="用户OpenID">{{ selectedRecord.user_openid || '无' }}</el-descriptions-item>
          <el-descriptions-item label="设备信息">{{ selectedRecord.device_info || '无' }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ selectedRecord.ip_address || '无' }}</el-descriptions-item>
          <el-descriptions-item label="User-Agent">{{ selectedRecord.user_agent || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <div v-if="selectedRecord.consume_note" style="margin-top: 20px;">
          <h4>核销备注</h4>
          <el-input 
            type="textarea" 
            :value="selectedRecord.consume_note" 
            readonly
            :rows="3"
          ></el-input>
        </div>
        
        <div v-if="selectedRecord.extra_data" style="margin-top: 20px;">
          <h4>扩展数据</h4>
          <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px;">{{ JSON.stringify(JSON.parse(selectedRecord.extra_data), null, 2) }}</pre>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="printRecord">打印凭证</el-button>
      </span>
    </el-dialog>

    <!-- 撤销核销对话框 -->
    <el-dialog
      title="撤销核销"
      :visible.sync="revokeDialogVisible"
      width="500px"
    >
      <el-form :model="revokeForm" label-width="100px">
        <el-form-item label="记录ID">
          <el-input :value="revokeForm.record_id" readonly></el-input>
        </el-form-item>
        <el-form-item label="撤销原因">
          <el-input 
            type="textarea" 
            v-model="revokeForm.revoke_reason"
            :rows="4"
            placeholder="请输入撤销原因"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="revokeDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmRevoke" :loading="revokeLoading">确认撤销</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getConsumeRecords, getConsumeStats, revokeCouponConsume, getConsumeRecordDetail, exportConsumeRecords, getMerchantList } from '@/api/nfc'

export default {
  name: 'CouponRecords',
  data() {
    return {
      searchForm: {
        merchant_id: '',
        coupon_code: '',
        dateRange: [],
        operated_by_merchant_staff: ''
      },

      // 商户列表
      merchantList: [],
      merchantLoading: false,
      
      records: [],
      pagination: {
        page: 1,
        limit: 20,
        total: 0
      },
      
      statsData: {
        total_records: 0,
        total_amount: 0,
        total_discount: 0
      },
      
      loading: false,
      exportLoading: false,
      
      // 排序
      sortField: '',
      sortOrder: '',
      
      // 对话框
      detailDialogVisible: false,
      selectedRecord: null,
      
      revokeDialogVisible: false,
      revokeForm: {
        record_id: null,
        revoke_reason: ''
      },
      revokeLoading: false
    }
  },
  watch: {
    // 监听路由变化，检测刷新参数
    '$route'(to) {
      if (to.path === '/nfc/coupon/records' && to.query.refresh) {
        // 重置分页到第一页
        this.pagination.page = 1
        // 刷新数据
        this.loadRecords()
      }
    }
  },
  mounted() {
    // 从查询参数中获取记录ID（如果有）
    const { id } = this.$route.query
    if (id) {
      this.viewRecordById(id)
    }

    this.loadMerchantList()
    this.loadRecords()
  },
  methods: {
    /**
     * 加载商户列表
     */
    async loadMerchantList() {
      this.merchantLoading = true
      try {
        const response = await getMerchantList()
        if (response.code === 200) {
          this.merchantList = response.data || []
        } else {
          this.$message.error(response.message || '获取商户列表失败')
        }
      } catch (error) {
        console.error('获取商户列表失败:', error)
        this.$message.error('获取商户列表失败')
      } finally {
        this.merchantLoading = false
      }
    },

    /**
     * 加载记录列表
     */
    async loadRecords() {
      this.loading = true
      
      try {
        const params = {
          page: this.pagination.page,
          limit: this.pagination.limit
        }

        // 只有选择了商户时才添加merchant_id参数
        if (this.searchForm.merchant_id) {
          params.merchant_id = this.searchForm.merchant_id
        }
        
        // 添加搜索条件
        if (this.searchForm.coupon_code) {
          params.coupon_code = this.searchForm.coupon_code
        }

        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.start_date = this.searchForm.dateRange[0]
          params.end_date = this.searchForm.dateRange[1]
        }

        if (this.searchForm.operated_by_merchant_staff) {
          params.operated_by_merchant_staff = this.searchForm.operated_by_merchant_staff
        }
        
        // 添加排序
        if (this.sortField) {
          params.sort_field = this.sortField
          params.sort_order = this.sortOrder
        }
        
        const response = await getConsumeRecords(params)
        
        this.records = response.data.records || []
        this.pagination.total = response.data.pagination.total || 0
        
        // 加载统计数据
        this.loadStats()
        
      } catch (error) {
        this.$message.error('加载记录失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.loading = false
      }
    },

    /**
     * 加载统计数据
     */
    async loadStats() {
      try {
        const params = {}

        // 只有选择了商户时才添加merchant_id参数
        if (this.searchForm.merchant_id) {
          params.merchant_id = this.searchForm.merchant_id
        }
        
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.start_date = this.searchForm.dateRange[0]
          params.end_date = this.searchForm.dateRange[1]
        }
        
        const response = await getConsumeStats(params)
        this.statsData = response.data.consume_stats || {}
        
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },

    /**
     * 重置搜索
     */
    resetSearch() {
      this.searchForm = {
        merchant_id: '',
        coupon_code: '',
        dateRange: [],
        operated_by_merchant_staff: ''
      }
      this.pagination.page = 1
      this.sortField = ''
      this.sortOrder = ''
      this.loadRecords()
    },

    /**
     * 导出记录
     */
    async exportRecords() {
      this.exportLoading = true
      
      try {
        const params = {
          format: 'csv'
        }

        // 只有选择了商户时才添加merchant_id参数
        if (this.searchForm.merchant_id) {
          params.merchant_id = this.searchForm.merchant_id
        }
        
        // 添加搜索条件
        if (this.searchForm.coupon_code) {
          params.coupon_code = this.searchForm.coupon_code
        }

        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.start_date = this.searchForm.dateRange[0]
          params.end_date = this.searchForm.dateRange[1]
        }

        if (this.searchForm.operated_by_merchant_staff) {
          params.operated_by_merchant_staff = this.searchForm.operated_by_merchant_staff
        }
        
        // 这里应该调用导出API，返回文件下载
        const response = await exportConsumeRecords(params)
        
        // 创建下载链接
        const blob = new Blob([response.data])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `coupon_consume_records_${new Date().getTime()}.csv`
        link.click()
        window.URL.revokeObjectURL(url)
        
        this.$message.success('导出成功')
        
      } catch (error) {
        this.$message.error('导出失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.exportLoading = false
      }
    },

    /**
     * 处理排序变化
     */
    handleSortChange({ prop, order }) {
      this.sortField = prop
      this.sortOrder = order === 'ascending' ? 'asc' : 'desc'
      this.pagination.page = 1
      this.loadRecords()
    },

    /**
     * 处理分页大小变化
     */
    handleSizeChange(val) {
      this.pagination.limit = val
      this.pagination.page = 1
      this.loadRecords()
    },

    /**
     * 处理页码变化
     */
    handleCurrentChange(val) {
      this.pagination.page = val
      this.loadRecords()
    },

    /**
     * 查看记录详情
     */
    viewRecord(record) {
      this.selectedRecord = record
      this.detailDialogVisible = true
    },

    /**
     * 根据ID查看记录
     */
    async viewRecordById(id) {
      try {
        const response = await getConsumeRecordDetail(id)
        this.selectedRecord = response.data
        this.detailDialogVisible = true
      } catch (error) {
        this.$message.error('加载记录详情失败')
      }
    },

    /**
     * 查看优惠券详情
     */
    viewCouponDetail(couponCode) {
      const query = {
        coupon_code: couponCode
      }

      // 只有选择了商户时才添加merchant_id参数
      if (this.searchForm.merchant_id) {
        query.merchant_id = this.searchForm.merchant_id
      }

      this.$router.push({
        path: '/nfc/coupon/detail',
        query
      })
    },

    /**
     * 处理更多操作
     */
    handleCommand(command) {
      const { action, row } = command
      
      switch (action) {
        case 'revoke':
          this.revokeRecord(row)
          break
        case 'print':
          this.printRecord(row)
          break
      }
    },

    /**
     * 撤销核销
     */
    revokeRecord(record) {
      this.revokeForm = {
        record_id: record.id,
        revoke_reason: ''
      }
      this.revokeDialogVisible = true
    },

    /**
     * 确认撤销
     */
    async confirmRevoke() {
      if (!this.revokeForm.revoke_reason.trim()) {
        this.$message.error('请填写撤销原因')
        return
      }
      
      this.revokeLoading = true
      
      try {
        await revokeCouponConsume({
          record_id: this.revokeForm.record_id,
          revoke_reason: this.revokeForm.revoke_reason,
          admin_id: this.$store.state.user.adminId
        })
        
        this.$message.success('撤销成功')
        this.revokeDialogVisible = false
        this.loadRecords()
        
      } catch (error) {
        this.$message.error('撤销失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.revokeLoading = false
      }
    },

    /**
     * 打印凭证
     */
    printRecord(record = null) {
      const recordData = record || this.selectedRecord
      if (!recordData) return
      
      // 创建打印内容
      const printContent = `
        <div style="text-align: center; font-family: Arial, sans-serif;">
          <h2>优惠券核销凭证</h2>
          <hr>
          <div style="text-align: left; margin: 20px;">
            <p><strong>记录ID：</strong>${recordData.id}</p>
            <p><strong>优惠券代码：</strong>${recordData.coupon_code}</p>
            <p><strong>优惠券名称：</strong>${recordData.coupon_name}</p>
            <p><strong>原价金额：</strong>¥${recordData.original_amount || '0.00'}</p>
            <p><strong>优惠金额：</strong>¥${recordData.discount_amount || '0.00'}</p>
            <p><strong>实际消费：</strong>¥${recordData.consume_amount || '0.00'}</p>
            <p><strong>核销时间：</strong>${recordData.consume_time}</p>
            <p><strong>操作员工：</strong>${recordData.operated_by_merchant_staff}</p>
            <p><strong>核销地点：</strong>${recordData.consume_location}</p>
          </div>
          <hr>
          <p style="font-size: 12px; color: #666;">此凭证仅作为核销记录，请妥善保管</p>
        </div>
      `
      
      // 打开新窗口并打印
      const printWindow = window.open('', '_blank')
      printWindow.document.write(printContent)
      printWindow.document.close()
      printWindow.focus()
      printWindow.print()
      printWindow.close()
    },

    /**
     * 获取核销类型文本
     */
    getConsumeTypeText(type) {
      const types = {
        1: '正常消费',
        2: '人工核销',
        3: '系统自动'
      }
      return types[type] || '未知'
    },

    /**
     * 获取核销类型标签类型
     */
    getConsumeTypeTag(type) {
      const tags = {
        1: 'success',
        2: 'warning',
        3: 'info'
      }
      return tags[type] || ''
    }
  }
}
</script>

<style scoped>
.coupon-records {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

/* 统计卡片样式 - 与dashboard保持一致 */
.statistics-cards {
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 24px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.amount {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.discount {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.records-card {
  margin-bottom: 30px;
}

.amount-info {
  font-size: 12px;
  line-height: 1.4;
}

.amount-info div {
  margin-bottom: 2px;
}

.pagination-wrapper {
  text-align: center;
  margin-top: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-card .el-form-item {
    margin-bottom: 15px;
  }

  .statistics-cards .el-col {
    margin-bottom: 15px;
  }
}</style>